/*            Copyright(c) 2006-2008 Dave Sexton           *
 * http://www.codeplex.com/DocProject                      *
 * http://www.codeplex.com/DocProject/Project/License.aspx *
 ***********************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.ComponentModel;

namespace DaveSexton.DocProject
{
	public static class Log
	{
		private static readonly EventLog log = new EventLog("Application", ".", "DocProject");

		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		public static void Exception(Exception ex, string message)
		{
			Exception(ex, message, null);
		}

		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		public static void Exception(Exception ex, string format, params object[] args)
		{
			if (args != null)
				format = string.Format(System.Globalization.CultureInfo.CurrentCulture, format, args);

			if (ex != null)
			{
				if (!string.IsNullOrEmpty(format))
					format = format + Environment.NewLine + Environment.NewLine + ex.ToString();
				else
					format = ex.ToString();
			}

			try
			{
				log.WriteEntry(format, EventLogEntryType.Error);
			}
			catch (Win32Exception innerEx)
			{
				if (DocProjectEnvironment.RunningInVisualStudio)
				{
					// This method is invoked by the DocProjectEnvironment class in the event of an initialization error, 
					// in which case it may have been the VSEnvironmentHost that failed.  Therefore, a catch-all
					// is used here so that the external code may process normally in the event that the
					// following code throws an exception.
					try
					{
						DocProjectEnvironment.ShowTrace();

						VSEnvironmentHost.TraceLine();
						VSEnvironmentHost.TraceLine(Resources.Text.LastErrorCouldNotBeLogged);
						VSEnvironmentHost.TraceLine(Resources.Text.LogError);
						VSEnvironmentHost.TraceLine();
						VSEnvironmentHost.TraceLine(innerEx.ToString());
						VSEnvironmentHost.TraceLine();
						VSEnvironmentHost.TraceLine();
						VSEnvironmentHost.TraceLine(Resources.Text.OriginalError);
						VSEnvironmentHost.TraceLine();
						VSEnvironmentHost.TraceLine(format);
					}
					catch
					{
					}
				}
			}
		}

		public static void Message(string text)
		{
			Message(text, null);
		}

		public static void Message(string format, params object[] args)
		{
			if (args != null)
				format = string.Format(System.Globalization.CultureInfo.CurrentCulture, format, args);

			log.WriteEntry(format, EventLogEntryType.Information);
		}
	}
}
